from flask_restful import Resource,reqparse,request
from flask_shop import models
from flask_shop.product import img_bp,product_api
from flask_shop import db
from flask import current_app
import hashlib
from time import time

class Products(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('name',type=str,location='args')
        args = parser.parse_args()
        name = args.get('name')
        if name:
            prod_list = models.Product.query.filter(models.Product.name.like(f'%{ name }%')).all()
        else:
            prod_list = models.Product.query.all()
        return {'status':200,'msg':'获取成功','data':[p.to_dict() for p in prod_list]}
    
    def post(self):
        try:
            #定义
            parser = reqparse.RequestParser()
            parser.add_argument('name',type=str,required=True,help='请输入商品名称')
            parser.add_argument('price', type=float, help='商品价格不能为空')
            parser.add_argument('number',type=int)
            parser.add_argument('introduce',type=str)
            parser.add_argument('weight',type=int)
            parser.add_argument('cid_one',type=int)
            parser.add_argument('cid_two',type=int)
            parser.add_argument('cid_three',type=int)

            parser.add_argument('pics',type=list,location='json')
            parser.add_argument('prod_dynamic',type=list,location='json')
            parser.add_argument('prod_static',type=list,location='json')

            args = parser.parse_args()

            prod = models.Product(
                name = args.get('name'),
                price=args.get('price'),
                number=args.get('number'),
                introduce=args.get('introduce'),
                weight=args.get('weight'),
                cid_one=args.get('cid_one'),
                cid_two=args.get('cid_two'),
                cid_three=args.get('cid_three'),
            )
            db.session.add(prod)
            db.session.commit()
            #保存图片
            for path in args.get('pics'):
                pic = models.Picture(
                    path = path,
                    pid = prod.id
                )
                db.session.add(pic)
                db.session.commit()
            #保存静态属性
            for static in args.get('prod_static'):
                static_attr = models.ProductAttr(
                    pid = prod.id,
                    aid = static.get('id'),
                    value = static.get('value'),
                    _type='static',
                )
                db.session.add(static_attr)
            #保存动态属性
            for static in args.get('prod_dynamic'):
                dynamic_attr = models.ProductAttr(
                    pid = prod.id,
                    aid = static.get('id'),
                    value = ','.join(static.get('value')),
                    _type='dynamic',
                )
                db.session.add(dynamic_attr)
            db.session.commit()
            return {'status':200,'msg':'添加成功'}
        except Exception as e:
            return {'status':400,'msg':'添加失败'}

class Product(Resource):
    def delete(self,id):
        prod = models.Product.query.get(id)
        if prod:
            db.session.delete(prod)
            db.session.commit()
        return {'status':200,'msg':'删除成功'}

product_api.add_resource(Products,'/get_prod_list/')
product_api.add_resource(Product,'/delete_prod/<int:id>/')


@img_bp.route('/upload/',methods=['POST'])
def upload_file():
     # 获取上传的文件，这个文件是一个文件对象
    img_file = request.files.get('file')
    if not img_file:
        return {'status':500,'msg':'文件不存在'}
    if allow_upload(img_file.filename):
        #图片的保存路径
        floder = current_app.config.get('UPLOAD_FOLDER')
        #生成一个文件名
        file_name = md5_file() + '.' + img_file.filename.rsplit('.',1)[1]
        #保存文件
        img_file.save(f'{floder}/{file_name}')
        #封装数据
        data = {
            'path':f'/static/upload/{file_name}',
            'url':f'http://127.0.0.1:5000/static/upload/{file_name}'
        }
        return {'status':200,'msg':'图片上传成功','data':data}
    else:
        return {'status':500,'msg':'图片文件类型不允许上传'}

def allow_upload(filename):
    return '.' in filename and filename.rsplit('.',1)[1] in current_app.config.get('ALLOWED_EXTENSIONS')

def md5_file():
    '''
    通过md5加密,对时间戳进行加密
    '''
    # 创建hashlib对象
    md5 = hashlib.md5()
    # 获取当前时间戳
    timestamp = str(time())
    # 对时间戳进行加密
    md5.update(timestamp.encode())
    # 获取加密后的字符串
    file_name = md5.hexdigest()
    return file_name 